package util

import (
	"strings"

	"mall/common/globalkey"
	"mall/common/utils/pointy"
	"mall/service/attachment/rpc/attachmentclient"
)

type Option struct {
	CanRemove  bool
	CanRestore bool

	CanPut       bool
	CanWatermark bool
	CanThumbnail bool
}

func GetOptionByStatusAndType(status *uint32, fileType *uint32) *Option { // #24.06.01# 完成：
	res := &Option{}

	if status != nil {
		switch int32(*status) {
		case globalkey.AttachmentStatusPublish:
			res.CanRemove = true
		case globalkey.AttachmentStatusInherit:
			res.CanRemove = true
		case globalkey.AttachmentStatusDraft:
			res.CanRemove = true
		case globalkey.AttachmentStatusPrivate:
			res.CanRemove = true
		case globalkey.AttachmentStatusTrash:
			res.CanRestore = true
		}
	}

	if fileType != nil {
		switch int32(*fileType) {
		case globalkey.AttachmentTypePutPendingFile, globalkey.AttachmentTypeWatermarkPendingFile,
			globalkey.AttachmentTypeThumbnailPendingFile, globalkey.AttachmentTypePendingFile:
			res.CanPut = true
		case globalkey.AttachmentTypeWatermarkPendingPutReadyFile, globalkey.AttachmentTypePendingPutReadyFile:
			res.CanWatermark = true
		case globalkey.AttachmentTypeThumbnailPendingPutReadyFile, globalkey.AttachmentTypePendingWatermarkReadyFile:
			res.CanThumbnail = true
		}
	}

	return res
}

func ParseSorter(sorter *string) (res []*attachmentclient.OrderBy) { // #24.06.01# 完成：
	if sorter == nil {
		return
	}

	sorters := strings.Split(*sorter, ";")
	if len(sorters) == 0 {
		return
	}

	for _, orderBy := range sorters {
		orderBys := strings.Split(orderBy, ":")

		if len(orderBys) == 2 {
			res = append(res, &attachmentclient.OrderBy{
				Field: orderBys[0],
				Order: orderBys[1],
			})
			continue
		}

		if len(orderBys) == 1 {
			res = append(res, &attachmentclient.OrderBy{
				Field: orderBys[0],
				Order: "0",
			})
		}
	}

	return
}

func ParseFilter(filter *string) (res []*attachmentclient.FilterBy) { // #24.06.01# 完成：
	if filter == nil {
		return
	}

	filters := strings.Split(*filter, ";")
	if len(filters) == 0 {
		return
	}

	for _, filterBy := range filters {
		filterBys := strings.Split(filterBy, ":")

		if len(filterBys) == 2 {
			res = append(res, &attachmentclient.FilterBy{
				Field: filterBys[0],
				In:    filterBys[1],
			})
		}
	}

	return
}

func ParseMeta(meta *string) (res []*attachmentclient.MetaInfo) { // #24.06.01# 完成：
	if meta == nil {
		return
	}

	if len(strings.TrimSpace(*meta)) == 0 {
		return
	}

	items := strings.Split(strings.TrimSpace(*meta), ";")
	if len(items) == 0 {
		return
	}

	for _, item := range items {
		parts := strings.Split(item, ":")

		if len(parts) == 2 && len(strings.TrimSpace(parts[0])) > 0 && len(strings.TrimSpace(parts[1])) > 0 {
			res = append(res, &attachmentclient.MetaInfo{
				Key:   pointy.GetPointer(strings.TrimSpace(parts[0])),
				Value: pointy.GetPointer(strings.TrimSpace(parts[1])),
			})
		}
	}

	return
}
